package net.avcompris.base.testutil.processes;

/**
 * This class gives the user a feedback about a running CLI process. The idea
 * is for instance
 * to print to the console ow many lines have been read from a database. 
 * 
 * @author David Andrianavalontsalama
 */
public class CliProgress {

	public CliProgress() {
		
	}
	
	public CliProgress(final String message) {
		
		System.out.println(message);
	}
	
	private final long start = System.currentTimeMillis();

	private int count = 0;

	private long next = start + 1000;

	private final StringBuffer sb = new StringBuffer();
	
	/**
	 * Tell the class the process is running, and a step is running. 
	 * This displays the current increment count, if one second was elapsed
	 * from the last time.
	 * 
	 * @return the current increment count.
	 */
	public int inc() {

		final long now = System.currentTimeMillis();

		++count;

		if (now > next) {

			sb.append(count);
			
			if (sb.length() > 80) {
				
				sb.setLength(0);
				
				System.out.println();
				
				sb.append(count);
			}
			
			sb.append(" ");
			
			System.out.print(count + " ");

			next = now + 1000;
		}
		
		return count;
	}

	/**
	 * Tell the class the process is done. This displays the total
	 * increments.
	 */
	public void end() {

		System.out.println();

		final long elapsed = System.currentTimeMillis() - start;

		System.out
				.println("Total: " + count + ", elapsed: " + elapsed + " ms.");
	}
}
